//用户小仓库
import { defineStore } from "pinia";
//引入接口及数据类型
//@ts-ignore
import { reqLogin, reqUserInfo } from "@/api/user";
import type { loginForm } from "@/api/user/type";
import type { UserState } from "@/store/modules/types/type";
//引入本地存储工具方法
import { SET_TOKEN, GET_TOKEN, DEL_TOKEN } from "@/utils/token";
//引入路由（常量路由）
import { constantRoute } from "@/router/routes";

let useUserStore = defineStore("User", {
  state: (): UserState => {
    return {
      token: GET_TOKEN(), //用户唯一标识token
      menuRoutes: constantRoute, //存储菜单需要的路由信息
      userDetail: null, //用户详细信息
    };
  },
  actions: {
    //用户登录方法
    async userLogin(data: loginForm) {
      let result: any = await reqLogin(data);
      if (result.code == 200) {
        this.token = result.data.token as string;
        SET_TOKEN(result.data.token as string);
        //保证async返回一个成功的promise
        return "ok";
      } else {
        return Promise.reject(new Error(result.data.message));
      }
    },
    //获取用户信息方法,TOKEN通过axios拦截器中发送header头实现，否则无法获取用户信息
    async userInfo() {
      //判断当前用户是否登录，如果未登录，跳转到登录页面
      let result: any = await reqUserInfo();
      if (result.code == 200) {
        this.userDetail = result.data.checkUser;
        return "ok";
      } else {
        return Promise.reject(new Error("用户信息失效，请重新登陆"));
      }
    },
    //退出登录方法,清除所有跟用户有关的仓库数据及本地存储数据
    async logOut() {
      let result: any = DEL_TOKEN();
      this.token = null;
      this.userDetail = null;
      if (
        result == undefined &&
        this.token == null &&
        this.userDetail == null
      ) {
        return "ok";
      } else {
        return Promise.reject(new Error("退出登录失败,请稍后重试"));
      }
    },
  },
  getters: {},
});

export default useUserStore;
